package com.seari.vehbaseF.client;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.TypeReference;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.commonutils.redis.ex.JedisNotInitializeException;
import com.seari.vehbaseF.bean.DeviceParamDataBean;
import com.seari.vehbaseF.mapper.RealDataMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
class RealDataHistoricalDataPrep {

    Logger logger = LoggerFactory.getLogger(RealDataHistoricalDataPrep.class);

    @Autowired
    RealDataMapper realDataMapper;

    @Scheduled(cron = "0 0 0/1 * * ?")
    //测试用 每分钟一次
//    @Scheduled(cron = "0 * * * * ?")
    public void realDataScheduler() {
        Jedis jedis = null;

        try {
            jedis = JedisUtilProxy.getJedis();
            jedis.select(2);

            Pipeline pipelined = jedis.pipelined();

            //获取Redis库中所有Key
            Set<String> redisKeys = jedis.keys("*");

            List<DeviceParamDataBean> deviceParamDataBeanList = new ArrayList<>();

            for (String key : redisKeys) {
                pipelined.get(key);
            }

            List<Object> res = pipelined.syncAndReturnAll();

            //依据Key获取对应的JSON数组对象
            //组装入库的集合数据
            for (Object re : res) {
                List<DeviceParamDataBean> singleDeviceDataList = JSONArray.parseObject((String) re,
                        new TypeReference<List<DeviceParamDataBean>>() {
                        });

                deviceParamDataBeanList.addAll(singleDeviceDataList);
            }

            int dataListSize = deviceParamDataBeanList.size();
            logger.info("历史数据集合组装完成， [count]={}", dataListSize);

            //集合数据切片入库
            for (int i = 0, j = 0, sec = 2000; i < dataListSize; i += sec) {
                j = i + sec;

                try {

                    if (j < dataListSize) {
                        realDataMapper.saveRealData(deviceParamDataBeanList.subList(i, j));
                    } else {
                        realDataMapper.saveRealData(deviceParamDataBeanList.subList(i, dataListSize));
                        break;
                    }

                } catch (Exception e) {
                    logger.error("数据库插入异常 ， [errMsg]={}", e.getMessage());
                }
            }

            logger.info("历史数据入库完成 。");

        } catch (JedisNotInitializeException e) {
            logger.error("Redis连接异常 ， [errMsg]={}", e.getMessage());
        } finally {
            jedis.close();
        }

    }
}
